<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Http\Requests\SettingRequest;

class SettingController extends CommonController
{
    /**
     * 获取系统设置列表
     */
    public function getIndex()
    {
        $lists = Setting::orderBy('id', 'asc')->paginate(10);

//        dd($lists);
        return view('setting.index')->with("lists", $lists)->with("actions", $this->actions);
    }

    /**
     * 执行一个搜索
     */
    public function search(Request $request)
    {
        $data = $request->input();
        $sql = Setting::orderBy('id', 'asc');

        if (isset($data['name']) && $data['name'] != '') {
            $sql->where('name', 'like', '%' . trim($data['name']) . '%');
        }

        if (isset($data['variable']) && $data['variable'] != '') {
            $sql->where('variable', 'like', '%' . trim($data['variable']) . '%');
        }

        if (isset($data['value']) && $data['value'] != '') {
            $sql->where('value', 'like', '%' . trim($data['value']) . '%');
        }

        if (isset($data['system']) && $data['system'] != '') {
            $sql->where('system', $data['system']);
        }

        $lists = $sql->paginate(10);

        return view('setting.search')->with("lists", $lists)->with("name", $data['name'])
            ->with("variable", $data['variable'])->with("value", $data['value'])
            ->with("system", $data['system'])->with("actions", $this->actions);

    }

    /**
     * 获取创建系统设置的页面
     */
    public function getCreate()
    {

        return view('setting.create');
    }

    /**
     * 执行一个系统参数的创建
     */
    public function postCreate(SettingRequest $request)
    {
        $data = $request->input();
//        dd($data);
        unset($data['_token'], $data['formType']);
        $result = Setting::create($data);
        //更新缓存
        Setting::cache(1);

        return AjaxCallbackMessage('恭喜,创建成功，新分类的id为' . $result->id, true, url('setting/index'));
    }

    /**
     * 获取编辑页面
     */
    public function getEdit(Request $request)
    {
        $data = $request->input();
        $me = Setting::where('id', $data['id'])->first();

        return view('setting.edit')->with('me', $me);
    }

    /**
     * 执行一个系统参数编辑
     */
    public function postEdit(SettingRequest $request)
    {
        $data = $request->input();
//        dd($data);
        $id = $data['id'];
        unset($data['id'], $data['_token'], $data['formType']);
        Setting::where('id', $id)->update($data);
        //更新缓存
        Setting::cache(1);

        return AjaxCallbackMessage('恭喜，修改成功', true, url('setting/index'));
    }

    /**
     * 执行删除
     */
    public function postDelete(Request $request)
    {
        $id = $request->input('sid');
        Setting::where('id', $id)->delete();
        //更新缓存
        Setting::cache(1);

        return AjaxCallbackMessage('恭喜，删除成功', true, url('setting/index'));
    }
}
